// pages/simple_map/simple_map.js
var app = getApp()
var QQMapWX = require('../../libs/qqmap-wx-jssdk.js')

var qqmapsdk = new QQMapWX({
  key: 'BYXBZ-763KX-YTT4S-7SEOC-N5I23-I5BAE'//申请的开发者秘钥key
});

var timer = null;
let map;
let userid = "";
let devCache = {};

//getLastInfo返回的信息
let deviceInfoList = {};
//出错的设备
let errorDevice = {};
//打开的设备
let turnOnDevice = [];
//未打开的设备
let turnOffDevice = [];
//在线的设备
let onlineDevice = [];
//不在线的设备
let offlineDevice = [];
let offlineDeviceStr = "";
//自动设备
let autoDevice = [];
//手动设备
let manualDevice = [];

//所有设备
let allDeviceNum = 0;

let postionCache = {};
let RefreshMap = true;
let firstInit = true;

let groups = [];
let expandList = [];

//展现在地图上的组
var RoadGroups = [];

// let offline_single = [];
// let offline_branch = [];
let online_single = [];
let online_branch = [];
let unusual_TurnOn = [];
let unusual_TurnOff = [];
let offline_branch = [];

let infoWin = null;
//地图标记组
// let markers = {};
let info = null;
let main_map = null;

//判断命令有没有执行成功的变量
var try_times = 0;
let reInterval = 5 * 1000;
let retimes = 3;

Page({
  /**
   * 页面的初始数据
   */
  data: {
    is_load_center_scale:false,
    detail_is_show:false,
    show_coverview_list: false, 
    current_info: '', 
    coverview_dev_list: [
    //  { 
    //   name: 'ceshi3333',
    //   id: 8,
    //   hidden: true,
    //   images: '/images/group.png',
    //   down: '/images/icon_down2x.png',
    //   points: [
    //     {
    //       devNo: '868221047652659',
    //       devName: 'ceshi123'
    //     }
    //   ]
    // }
    ], 
  
    latitude: '',
    longitude: '',
    default_latitude:'',
    default_longitude:'',   
    mapCtx:'',
    scale:16,
    ws:'',
    wxst:'',
    dev_list_detail:[
      /**测试数据 需要删除 */
      // {
      //   secondTurnOffTime: '12:00:00',
      //   devNo: '868221047652659',
      //   latitude: '32.409080',
      //   type:1,
      //   firstTurnOnTime: '12:30:00',
      //   devCurrentTime: '11:30:30',
      //   longitude:'119.420090' ,
      //   firstOrSumElec: '100',  //第一路电流或者总电流 单位毫安
      //   secondTurnOnTime: '10:00:00',
      //   auto: true,
      //   onLine: true,
      //   secondElec:'100', //第二路电流（预留）
      //   firstSwitch: true,  //第一路开关
      //   firstTurnOffTime: '13:30:00',
      //   secondSwitch: false,  //第二路开关
      //   description: 'ceshi_del'
      // }      
    ],
    markers: [
       /**测试数据 需要删除 */
      // {
      //   id: '868221047652659',
      //   latitude: '32.409080',
      //   longitude: '119.420090',
      //   name: '868221047652659',
      //   iconPath: '../../images/on_marker.png',
      //   callout: {
      //     content: '编号868221047652659',
      //     padding: '8rpx',
      //     borderRadius: 5,
      //     borderWidth: 1,
      //     borderColor: "#000000",
      //     bgColor: "#c9c9c9"
      //   }
      // }
    ],
    address:'',
    is_show_tips:true,
    cur_mode_array: ['手动', '自动'],
    /**模式默认的值 默认是手动 */
    cur_mode_index: 0,
    cur_mode_item: '手动',
    cur_operator: ['合上', '断开'],
    /**状态默认值  默认是合上*/
    cur_operator_index: 0,
    cur_operator_item: '合上',
   
    mode_disabled: false,
    switch_disabled: false,
    // turnon_disabled: false,
    // turnoff_disabled: false,
    cur_onLine:false,
    cur_status:'',
    devices_str:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    
    //var events = require('events'); 
    //var emitter = new events.EventEmitter(); 
    //const emitter = EventEmitter()//获取eventEmitter对象
    
    //emitter.setMaxListeners(500)//指定一个最大监听数量 
 
    that.disLoad();
    that.load('请稍等...');

    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        var latitude = res.latitude;
        var longitude = res.longitude;

        that.setData({
          // latitude: res.latitude,
          // longitude: res.longitude,
          default_latitude: res.latitude,
          default_longitude: res.longitude
        });
      }
    }); 
  },

  refreshInfo:function(){
    let that = this;

    var header = {
      'content-type': 'application/x-www-form-urlencoded',
      'cookie': "openid=" + app.globalData.openid
    };

    wx.request({
      url: "https://119.3.46.145/server/FindDevice",
      method: "post",
      header:header,
      data: {
        userid: app.globalData.userid
      },
      success: res=> {
        let devs = JSON.parse(res.data.data);
        allDeviceNum = devs.length;
       
        app.globalData.allDeviceNum = allDeviceNum;             

        wx.request({
          url: "https://119.3.46.145/server/GetLastInfo",
          method: "post",
          header:header,
          data: {
            devNo: devs + ""
          },
          success:res=>{
            let objs = JSON.parse(res.data.data);
            for (let i in objs) {
              that.CheckDevice(objs[i]);
            }

            app.globalData.onlineDeviceNum = onlineDevice.length;
            app.globalData.turnonDeviceNum = turnOnDevice.length 
          
          },
          fail:error=>{
            console.log(error, 'GetLastInfo error')
          }
        })
      },
      fail:error=>{      
        console.log(error, 'FindDevice error')
      }
    });
  },

  refreshBranch:function(){
    let that = this;
    let header = {
      'content-type': 'application/x-www-form-urlencoded',
      'cookie': "openid=" + app.globalData.openid
    };
    let tmp_markers_arr = [];
    wx.request({
      //url: "https://119.3.46.145/server/GetIndexStatistics",
      url:app.globalData.url+"GetAllBranchState",
      type: "post",
      header:header,
      data: {
        userid: app.globalData.userid,
        page:1,
        rows:400,
        areaKey:"",
        devKey:""
      },
      success: function (response) {        
        //console.log(response, 'response')
        let rows = response.data.rows

        if (rows == undefined) {
          that.geo();// 设置地图默认中心
          that.disLoad();
          return;
        } 

        if (rows.length == 0){
          that.geo();// 设置地图默认中心
          return;
        } 

        for (let i in rows) {
          let item = rows[i]
          let iconPath_src = ''        
          let status = ""
          let switchStatus = ""
          

          if(item.devState.indexOf("离线")!=-1){           
            iconPath_src = '../../images/off_line.png'
            status = '离线'      
            switchStatus = "离线设备暂无终端状态"     
          }
          if(item.devState.indexOf("在线")!=-1){          
            iconPath_src =  '../../images/on_marker.png'
            status = '在线'
            let tmp_switchStatus = item.switchState
            tmp_switchStatus.forEach(function(item,index){
              if(item===false){
                //switchStatus +="⚐ " 
                switchStatus +=" ⚐"
              }
              if(item===true){
                switchStatus +=" ⚑"
              }
            })

            switchStatus += "   (⚐断开 ⚑合上)"
          }
          
          let callout_str = "路段名: " + item.groupName + "\r\n" + "开关状态:" + switchStatus + "\r\n" + "终端电压:[A相: " + item.VoltA + "] [B相: " + item.VoltB + "] [C相: "+ item.VoltC+"]\r\n"+"状态: "+status;
        
          let tmp_markers_item = {
            id: item.mac,
            latitude: item.latitude,
            longitude: item.longitude,                      
            //iconPath: item.devState. ? '../../images/off_marker.png' : '../../images/on_marker.png',
            iconPath:iconPath_src,
            width:24,
            height:24,
            // name: item.Name,
            callout: {
              content: callout_str,
              padding: '5px 5px',
              borderRadius: 5,
              borderWidth: 1,
              borderColor: "#000000",
              // bgColor: "#c9c9c9"        
            }
          };
          //console.log(tmp_markers_item, "tmp_markers_item");
          tmp_markers_arr.push(tmp_markers_item); 
        }

        that.setData({
          markers: tmp_markers_arr
        }); 

        //console.log(that.data.markers);
    
    //只在show时候做一次设置中心点和缩放比
        if (!that.data.is_load_center_scale){
        
          //设置中心点  
          that.getMapCenter();
    
          //设置缩放比  
          that.getMapScale();
    
          that.setData({
            is_load_center_scale:true
          });
        } 
    
        //取消loading
        that.disLoad();
      }
    });

  },

  //最新刷新函数
  refreshLogSize:function() {    
    let that = this;
    let header = {
      'content-type': 'application/x-www-form-urlencoded',
      'cookie': "openid=" + app.globalData.openid
    };
    wx.request({
      //url: "https://119.3.46.145/server/GetIndexStatistics",
      url:app.globalData.url+"GetIndexStatistics",
      type: "post",
      header:header,
      data: {
        userid: app.globalData.userid
      },
      success: function (response) {        
        let obj = response.data;         
        // offline_single = JSON.parse(obj.offline_single_devs);
        // offline_branch = JSON.parse(obj.offline_branch_devs);
        online_single = JSON.parse(obj.online_single_devs);
        online_branch = JSON.parse(obj.online_branch_devs);
        offline_branch = JSON.parse(obj.offline_branch_devs);
        offlineDeviceStr = offline_branch.join(",");

        unusual_TurnOn = JSON.parse(obj.unusual_TurnOn);
        unusual_TurnOff = JSON.parse(obj.unusual_TurnOff);
        wx.request({
          //url: "https://119.3.46.145/server/GetGroups",
          url:app.globalData.url+"GetGroups",
          type: "post",
          header:header,
          data: {
            userid: app.globalData.userid
          },
          success: function (response) {
            if (response.data.data == undefined) {
              that.geo();// 设置地图默认中心
              that.disLoad();
              return;
            }  

            RoadGroups = JSON.parse(response.data.data);  

            if (RoadGroups.length == 0){
              that.geo();// 设置地图默认中心
              return;
            }          
            
            for (let p in RoadGroups) {            
              if (RoadGroups[p].hasOwnProperty("devs")) {
                let unusual = false;
                let array = RoadGroups[p].devs;
                for (let i = 0; i < array.length; i++) {
                  let devNo = array[i].split("_")[1];

                  if (unusual_TurnOff.indexOf(devNo) !== -1) {                 
                    unusual = true;
                    break;
                  }
                  if (unusual_TurnOn.indexOf(devNo) !== -1) {
                 
                    unusual = true;
                    break;
                  }
                  if (online_single.indexOf(devNo) === -1) {                 
                    unusual = true;
                    break;
                  }
                  if (online_branch.indexOf(devNo) === -1) {
                    unusual = true;
                    break;
                  }
                }

                if (unusual) {
                  RoadGroups[p].unusual = true;
                }
                else {                
                  RoadGroups[p].unusual = false;
                }
              }
            }            
         
            that.loadGroup();
            // loadTable();
          },
          fail:function(error){
            console.log(error, "error GetGroups");
          }       
        });
      }
    });
  },

  CheckDevice:function(obj) {
    let devNo = obj.devNo;
    let state = 0;
    //记录下最新返回的状态
    deviceInfoList[devNo] = obj;

    //检查是否在线
    let online = obj.OnLine;
    if (online) {
      state = 1;
      //判断在线列表中是否存在该设备，不在添加
      if (onlineDevice.indexOf(devNo) === -1) {
        onlineDevice.push(devNo);
      }
      //判断不在线列表是否存在该设备,在就删除
      if (offlineDevice.indexOf(devNo) !== -1) {
        offlineDevice.splice(offlineDevice.indexOf(devNo), 1);
      }
    }
    else {
      state = 0;
      //和在线相反
      if (offlineDevice.indexOf(devNo) === -1) {
        offlineDevice.push(devNo);
      }
      if (onlineDevice.indexOf(devNo) !== -1) {
        onlineDevice.splice(onlineDevice.indexOf(devNo), 1);
      }
    }

    //是否为自动模式
    let auto = obj.Auto;
    if (auto) {
      if (autoDevice.indexOf(devNo) === -1) {
        autoDevice.push(devNo);
      }
      if (manualDevice.indexOf(devNo) !== -1) {
        manualDevice.splice(manualDevice.indexOf(devNo), 1);
      }
    }
    else {
      if (manualDevice.indexOf(devNo) === -1) {
        manualDevice.push(devNo);
      }
      if (autoDevice.indexOf(devNo) !== -1) {
        autoDevice.splice(autoDevice.indexOf(devNo), 1);
      }
    }

    //检查设备开关状态
    let switch_state = obj.FirstSwitch;
    if (switch_state) {
      if (state > 0)
        state = 2;
      if (turnOnDevice.indexOf(devNo) === -1) {
        turnOnDevice.push(devNo);
      }
      if (turnOffDevice.indexOf(devNo) !== -1) {
        turnOffDevice.splice(turnOffDevice.indexOf(devNo), 1);
      }
    }
    else {
      if (state > 0)
        state = 1;
      if (turnOffDevice.indexOf(devNo) === -1) {
        turnOffDevice.push(devNo);
      }
      if (turnOnDevice.indexOf(devNo) !== -1) {
        turnOnDevice.splice(turnOnDevice.indexOf(devNo), 1);
      }
    } 
  },

  loadGroup:function() {
    let that = this;    
    let tmp_markers_arr = [];
    for (let i in RoadGroups) {
      let item = RoadGroups[i]; 

      let devs = item.devs;
      let unusual_TurnOn_size = 0;
      let unusual_TurnOff_size = 0;
      let offline_single_size = 0;
      let offline_branch_size = 0;
      let single_size = 0;
      let branch_size = 0;
      for (let p in devs) {
        let no = devs[p];
        let no_list = no.split("_");
        if (no_list[0] == 0)
          single_size++;
        if (no_list[0] == 1)
          branch_size++;

        no = no_list[1];
        if (unusual_TurnOn.indexOf(no) !== -1)
          unusual_TurnOn_size++;
        if (unusual_TurnOff.indexOf(no) !== -1)
          unusual_TurnOff_size++;
        // if (offline_single.indexOf(no) !== -1)
        //   offline_single_size++;
        // if (offline_branch.indexOf(no) !== -1)
        //   offline_branch_size++;
        if(no_list[0] == 0 && online_single.indexOf(no) === -1)
          offline_single_size++;
        if(no_list[0] == 1 && online_branch.indexOf(no) === -1)
          offline_branch_size++;
      }

      // let callout_str = item.Name + "\r\n" + "描述:" + item.Description + "\r\n" + "单灯数量(台)：" + single_size + "[离线(台)" + offline_single_size + "]\r\n" + "支路数量(台)：" + branch_size + "[离线(台)" + offline_branch_size + "]\r\n" + "异常亮灯(台):" + unusual_TurnOn_size + "\r\n" + "异常关灯(台):" + unusual_TurnOff_size;

       let callout_str = item.Name + "\r\n" + "描述:" + item.Description + "\r\n" + "单灯数量(台)：" + single_size + "[离线(台)" + offline_single_size + "]\r\n" + "支路数量(台)：" + branch_size + "[离线(台)" + offline_branch_size + "]\r\n" + "异常亮灯(台):" + unusual_TurnOn_size + "\r\n" + "异常关灯(台):" + unusual_TurnOff_size;
       if(item.unusual != undefined){
         //console.log(item.unusual)
         //console.log(item, 'item')
       }
      let tmp_markers_item = {
        id: item.id,
        latitude: item.Latitude,
        longitude: item.Longitude,                      
        iconPath: item.unusual ? '../../images/off_marker.png' : '../../images/on_marker.png',
        width:24,
        height:24,
        // name: item.Name,
        callout: {
          content: callout_str,
          padding: '10rpx 10rpx',
          borderRadius: 5,
          borderWidth: 1,
          borderColor: "#000000",
          // bgColor: "#c9c9c9"        
        }
      };
      tmp_markers_arr.push(tmp_markers_item);     
    }

    that.setData({
      markers: tmp_markers_arr
    }); 

//只在show时候做一次设置中心点和缩放比
    if (!that.data.is_load_center_scale){
      //设置中心点  
      that.getMapCenter();

      //设置缩放比  
      that.getMapScale();  

      that.setData({
        is_load_center_scale:true
      });
    }   


    //取消loading
    that.disLoad();
    
  },

  loadTable:function () {
    let that = this;

    for(let i = 0;i<RoadGroups.length;i++)
    {
      RoadGroups[i].work = "";

      if (RoadGroups[i].unusual) {
        let tmp = RoadGroups[i];
        RoadGroups.splice(0, 0, tmp);
        RoadGroups.splice(i + 1, 1);
      }
    }
   

    let tmp_show_coverview_list = that.data.show_coverview_list;

    that.setData({
      show_coverview_list: !tmp_show_coverview_list
    });

    if (!tmp_show_coverview_list == true) {
      //展示列表
    }
    if (!tmp_show_coverview_list == false) {
      //影藏设备列表   
      return;
    }

    that.setData({
      coverview_dev_list: RoadGroups
    }); 
    
},

  loadGroup_bak:function()
  {
    let that = this;
    let header = {
      'content-type': 'application/x-www-form-urlencoded',
      'cookie': "openid=" + app.globalData.openid
    };
   
    wx.request({
      //url: "https://119.3.46.145/server/GetGroups",    
      url:app.globalData.url+"GetGroups",
      method: "post",
      header:header,
      data: {
        userid: app.globalData.userid
      },
      success: res=> {      
        RoadGroups = JSON.parse(res.data.data);
        //[{Description: "测试路段123321",Latitude: 32.37423,Longitude: 119.39352,Name: "测试路段",SingleLightSize: 8,id: "1"},{Description: "测试路段2",Latitude: 33.696922,Longitude: 119.04785,Name: "测试路段2",id: "4"},{Description: "delete",Latitude: 119.39823,Longitude: 119.39823,Name: "测试路段13",id: "42"}]
        let tmp_markers_arr = [];
        for (let i in RoadGroups) {
          let item = RoadGroups[i];

          let callout_str = item.Name + "\r\n" + "描述:" + item.Description + "\r\n" + "单灯数量：" + item.SingleLightSize;

          let tmp_markers_item = {
            id:item.id,
            latitude: item.Latitude,
            longitude: item.Longitude,
            // name: item.Name,
            callout: {
              content: callout_str,
              padding: '10rpx 10rpx',
              borderRadius: 5,
              borderWidth: 1,
              borderColor: "#000000",
              bgColor: "#c9c9c9"
            }
          };

          tmp_markers_arr.push(tmp_markers_item);
        }

        that.setData({
          markers: tmp_markers_arr
        });    

       


        //设置中心点  
        //that.getMapCenter();

        //设置缩放比  
        //that.getMapScale();


        //取消loading
        that.disLoad();
      }
    })
  },

  onPointTap:function(e){   
    let that = this;  

    that.setData({
      is_show_tips:false
    });
  
    //let marker_id = parseInt(e.markerId)-1;   
    let marker_id = e.markerId;
    //let marker = that.data.markers[marker_id]; 
    let marker = {};
 
    that.data.markers.forEach(function(item, index){
      if(item.id == marker_id){
        marker = item;
        return false;
      }
    });

    if (marker.iconPath == "../../images/off_marker.png"){
      that.setData({
        tap_control_stauts:"在线 关闭"
      });
    }

    if (marker.iconPath == "../../images/off_line.png") {
      that.setData({
        tap_control_stauts: "不在线"
      });
    }

    if (marker.iconPath == "../../images/on_marker.png") {
      that.setData({
        tap_control_stauts: "在线 合上"
      });
    }

    let tmp_current = {};    
    that.data.dev_list_detail.forEach(function(_item, _index){
      if(_item.devNo == marker_id){
        tmp_current = _item;
        return false;
      }
    });   

    

    //逆解析城市
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: marker.latitude,
        longitude: marker.longitude
      },
      success: function (res) {
        //获取当前地址成功
        // console.log(res, "res 逆解析");
        // let markers_arr = that.data.markers;
       
        // markers_arr.forEach(function(item, index, self){
        //   console.log(item.callout, "item");
        //   if (item.id == marker_id){
        //     item.callout.content += "地址:\r\n";
        //     item.callout.content += res.result.address
        //     return false;
        //   }
        // });


        that.setData({
          address: res.result.address,
          // markers: markers_arr
        });
      },
      fail: function (res) {
        console.log('获取当前地址失败');
      }
    });     

    that.setData({
      tap_control_longtitude: marker.longitude,
      tap_control_latitude: marker.latitude,
      current_info: tmp_current,
      detail_is_show:true
    });

    /**['手动', '自动']*/
    if (that.data.current_info.auto == true) {
      that.setData({
        cur_mode_index: 1,
        cur_mode_item: "自动"
        //cur_operator_index: 0,        
      });
    }

    /**['合上','断开'], */
    if (that.data.current_info.onLine == false) {
      that.setData({
        cur_operator_index: 1,
        cur_operator_item: "断开"
      });
    }

    if (that.data.current_info.onLine == false) {
      that.setData({
        mode_disabled: true,
        switch_disabled: true,
        // turnon_disabled: true,
        // turnoff_disabled: true
      });     
    }

    if (that.data.current_info.onLine == true) {
      that.setData({
        cur_onLine:true
      });
    }

    if(that.data.current_info.onLine == false){
      that.setData({
        cur_status:'离线'
      });
    }
    else{
      if(that.data.current_info.firstSwitch == true){
        that.setData({
          cur_status: '在线 已合上'
        });
      }

      if (that.data.current_info.firstSwitch == false) {
        that.setData({
          cur_status: '在线 已断开'
        });
      }
    }

    // if (that.data.current_info.onLine == false) {
    //   wx.showModal({
    //     title: '提示',
    //     content: '离线设备只能设置经纬度',
    //   })
    // }
  },

  //点击右上角按钮 回到中心点 回到计算出来的scale
  coverImageTocenter:function(){
    // 中心点
    let that = this;
    var mapCtx = wx.createMapContext('myMap');   
    that.setData({
      mapCtx: mapCtx
    });

    mapCtx.moveToLocation({
      latitude:that.data.latitude,
      longitude:that.data.longitude,
      success(res) {      
        
      }
    });

    let tmp_scale = that.data.scale;
    that.setData({
      scale:tmp_scale
    });
  },

  goto_edit:function(e){
    let that = this;
    let name = e.currentTarget.dataset.name;
    let area = e.currentTarget.dataset.area;
    let onTime = e.currentTarget.dataset.ontime;
    let offTime = e.currentTarget.dataset.offtime;
    let admin = e.currentTarget.dataset.admin;
    let phone = e.currentTarget.dataset.phone;
    let unusual = e.currentTarget.dataset.unusual;
    wx.navigateTo({
      url: '../preview_loadgroup/preview_loadgroup?name='+name+'&area='+area+'&onTime='+onTime+'&offTime='+offTime+'&admin='+admin+'&phone='+phone+'&unusual='+unusual,
    })
  },

  isOpen: function (e) {
    var that = this;
    var idx = e.currentTarget.dataset.index;

    var dev_list = that.data.coverview_dev_list;

    // var curId = 0;
    dev_list.forEach(function (item, index, self) {
      if (idx == item.id) {
        if (item.hidden == true && item.down == "/images/icon_down2x.png") {
          item.down = "/images/icon_up2x.png";
        } else {
          item.down = "/images/icon_down2x.png";
        }
        item.hidden = !item.hidden;
        // curId = i;
      } else {
        item.hidden = true;
        item.down = "/images/icon_down2x.png";
      }
    });
    // }
    that.setData({
      coverview_dev_list: dev_list
    });
  },

  //单击右上角列表图标数显列表 点击列表可以调到指定的marker
  coverImageList:function(){
    let that = this;

    let tmp_show_coverview_list = that.data.show_coverview_list;

    that.setData({
      show_coverview_list: !tmp_show_coverview_list
    });    

    if (!tmp_show_coverview_list == true){
      //展示列表
    }
    if (!tmp_show_coverview_list == false){
      //影藏设备列表   
      return;
    }
   
    var header = {
      'content-type': 'application/x-www-form-urlencoded',
      'cookie': "openid=" + app.globalData.openid
    };

    wx.request({
      //url: 'https://119.3.46.145/server/FindGroup?userid=' + app.globalData.userid,
      url:app.globalData.url+"FindGroup?userid="+app.globalData.userid,
      method: 'POST',
      header: header,
      success: res => {
        let groups = JSON.parse(res.data.data);
        wx.request({
          //url: 'https://119.3.46.145/server/FindDevice?userid=' + app.globalData.userid,
          url:app.globalData.url + "FindDevice?userid=" + app.globalData.userid,
          method: 'POST',
          header: header,
          success: res => {           

            let devices = JSON.parse(res.data.devices);
            let devCache = [];

            let points = [];
            for (let i in devices) {
              let dev = devices[i];
              let groupname = "";
              for (let j = 0; j < groups.length; j++) {
                if (groups[j].groupId == dev.groupId) {
                  groupname = groups[j].groupName;
                  break;
                }
              }

              devCache[dev.devNo] = {
                name: dev.description,
                groupId: dev.groupId
              };

              let is_onLine = false;
              let is_firstSwitch = false;
              let longitude ='';
              let latitude = '';

              that.data.dev_list_detail.forEach(function (item, index, self) {
                if (item.devNo == dev.devNo) {
                  is_onLine = item.onLine;
                  is_firstSwitch = item.firstSwitch;
                  longitude = item.longitude;
                  latitude = item.latitude;
                  return false;
                }
              });

              let hasclass = false;
              for (let p in points) {
                let item = points[p];
                if (item.id === dev.groupId) {
                  let childpoints = item.points; 
                  childpoints.push({
                    devNo: dev.devNo,
                    devName: dev.description,
                    onLine:is_onLine,
                    firstSwitch:is_firstSwitch,
                    longitude: longitude,
                    latitude:latitude
                  });
                  hasclass = true;
                }
              }

              if (!hasclass) {
                points.push({
                  name: groupname,
                  id: dev.groupId,
                  hidden: true,
                  images: '/images/group.png',
                  down: '/images/icon_down2x.png',
                  points: [
                    {
                      devNo: dev.devNo,
                      devName: dev.description,
                      onLine: is_onLine,
                      firstSwitch: is_firstSwitch,
                      longitude: longitude,
                      latitude:latitude
                    }
                  ]
                })
              }
            }

            that.setData({
              coverview_dev_list: points
            });
          },
          fail: function (error) {
            console.log(error, "FindDevice error");
          }
        })
      },
      fail: function (error) {
        console.log(error, "FindDevice error");
      }
    });
  },

  goto_map_marker:function(info){   
    let that = this;

    that.setData({
      show_coverview_list: false
    });
    let current_lat = info.currentTarget.dataset.lat;
    let current_long = info.currentTarget.dataset.long;
  
    var mapCtx = wx.createMapContext('myMap');

    if (current_lat == undefined || current_long == undefined){
      wx.showModal({
        title: '提示',
        content: '当前地图上暂无该点！',
      })
      return;
    }

    mapCtx.moveToLocation({
      latitude: current_lat,
      longitude: current_long,
      success(res) {
        // console.log("转到指定的marker");
      }
    });   
  },

  sendRegisterDevice:function(devices_str){
    let that = this;

    var header = {
      'content-type': 'application/x-www-form-urlencoded',
      'cookie': "openid=" + app.globalData.openid
    };

    wx.request({
      //url: 'https://119.3.46.145/server/RegisterDevice?devNo=' + devices_str,
      url:app.globalData.url+"RegisterDevice?devNo=" + devices_str,
      header: header,
      success: res => {
        //console.log(res);
      },
      fail: function (err) {

      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this;
   
    //每次打开页面都会做
    //that.loadGroup();   
    that.setData({
      is_load_center_scale:false
    });
    //that.refreshLogSize();
    that.refreshBranch()

    //最新改变 把定时器放到这儿来 原来再onload那儿 其余onshow函数没变 
    timer = setInterval(function () {
      //console.log("setInterval is ing")

      //that.refreshLogSize();    
      that.refreshBranch()
    }, 60 * 1000);

  },
  dev_general:function(){
    let that = this;
    wx.navigateTo({
      url: '../dev_general/dev_general'
    })
  
  },
  
  
  
  connect:function(e){
    let that = this;
    let devNo = e.currentTarget.dataset.devid;
   
    if (app.globalData.onlineDevice.indexOf(devNo) === -1) {  
      wx.showModal({
        title: '提示',
        content: '设备离线状态,无法发送指令到设备',
      })
      return;
    }
  
    if (app.globalData.turnOffDevice.indexOf(devNo) !== -1 && app.globalData.turnOnDevice.indexOf(devNo) === -1) {
      //合上开关
      that.turnOn(devNo);
      // info.close();
    } else {
      //alert("开关已合上 " + no);
      wx.showModal({
        title: '提示',
        content: '开关已合上'+devNo,
      });
      
    }
  },
  
  disconnect:function(e){
    let devNo = e.currentTarget.dataset.devid;
    let that = this;
   
    if (app.globalData.onlineDevice.indexOf(devNo) === -1) {  
      wx.showModal({
        title: '提示',
        content: '设备离线状态,无法发送指令到设备',
      })
      return;
    }
  
    if (app.globalData.turnOffDevice.indexOf(devNo) === -1 && app.globalData.turnOnDevice.indexOf(devNo) !== -1) {
      //断开开关
      that.turnOff(devNo);
      // info.close();
    } else {
      wx.showModal({
        title: '提示',
        content: "开关已断开 " + devNo,
      })
    }
  },
  
  
  //切换模式 
  change_mode:function(e){
    //true 自动 false 手动
    let that = this;
    let cur_mode = e.currentTarget.dataset.mode;
    let devNo = e.currentTarget.dataset.devid;
  
    if (app.globalData.onlineDevice.indexOf(devNo) === -1) {
      wx.showModal({
        title: '提示',
        content: '当前设备不在线，操作失败',
      });
      return;
    }
  
   /**切换就需要取反 !cur_mode==false表示当前是自动 切换后成为手动; !cur_mode==true表示当前是手动 切换后成为自动;*/
  
    if (app.globalData.autoDevice.indexOf(devNo) !== -1) {
      //切换到手动模式
      that.setManual(devNo);
    }  
    
    if (app.globalData.manualDevice.indexOf(devNo) !== -1) {
      //切换到自动模式
      that.setAuto(devNo);
    }
  },
  
  turnOn:function(devNo)
  {
    let that = this;
    that.disLoad();
    that.load("正在操作请稍等");
  
    if(app.globalData.onlineDevice.indexOf(devNo) === -1)
    {
      // $.messager.alert("提示", '当前设备不在线，操作失败');
      wx.showModal({
        title: '提示',
        content: '当前设备不在线，操作失败'
      })
      that.disLoad();
      return;
    }  
  
    wx.request({
      //url: 'https://119.3.46.145/server/m_set_dev_on?devId=' + devNo,
      url:app.globalData.url + "m_set_dev_on?devId=" + devNo,
      method: 'POST',
      header: var_header,
      success: res => {
        setTimeout(function () {
          if (app.globalData.turnOnDevice.indexOf(devNo) === -1) {
            try_times++;
            if (try_times <= retimes) {
              that.turnOn(devNo);
            }
            else {
              try_times = 0;           
              wx.showModal({
                title: '提示',
                content: '操作失败',
              });
              that.disLoad();
            }
          }
          else {        
            wx.showModal({
              title: '提示',
              content: '操作成功'
            });
            that.disLoad();
  
            let tmp_current_info = that.data.current_info;
            tmp_current_info.firstSwitch = true;
  
            let tmp_markers = that.data.markers;
            
            tmp_markers.forEach(function(item, index, self){
              if(item.devNo == devNo){
                item.iconPath = "../../images/on_marker.png";
                return false;  
              }
            });
  
            let tmp_cur_status = that.data.cur_status;
  
            if(that.data.current_info.onLine == true){
              tmp_cur_status = "在线 已合上";
            }
  
            if (that.data.current_info.onLine == false) {
              tmp_cur_status = "离线";
            }          
  
            that.setData({
              current_info: tmp_current_info,
              markers: tmp_markers,
              cur_status: tmp_cur_status
            });
          }
        }, reInterval);
      },
      fail: function (error) {
        console.log(error, "FindDevice error");
      }
    });
  },
  
  
  turnOff:function(devNo) {
    let that = this;
    that.disLoad();
    that.load("正在操作，请等待！");
  
    if (app.globalData.onlineDevice.indexOf(devNo) === -1) {
      // $.messager.alert("提示", '当前设备不在线，操作失败');
      wx.showModal({
        title: '提示',
        content: '当前设备不在线，操作失败'
      })
      that.disLoad();
      return;
    }
  
    wx.request({
      //url: 'https://119.3.46.145/server/m_set_dev_off?devId=' + devNo,
      url:app.globalData.url + "m_set_dev_off?devId=" + devNo,
      method: 'POST',
      header: var_header,
      success: res => {
        setTimeout(function () {
          if (app.globalData.turnOffDevice.indexOf(devNo) === -1) {
            try_times++;
            if (try_times <= retimes) {
              that.turnOff(devNo);
            }
            else {
              try_times = 0;
              // alert("操作失败");
              wx.showModal({
                title: '提示',
                content: '操作失败',
              })
              that.disLoad();
            }
          }
          else {
            // alert("操作成功");
            wx.showModal({
              title: '提示',
              content: '操作成功'
            })
            that.disLoad();
  
            let tmp_current_info = that.data.current_info;
            tmp_current_info.firstSwitch = false;
  
            let tmp_markers = that.data.markers;
  
            tmp_markers.forEach(function (item, index, self) {
              if (item.devNo == devNo) {
                item.iconPath = "../../images/off_marker.png";
                return false;
              }
            });
  
            let tmp_cur_status = that.data.cur_status;
  
            if (that.data.current_info.onLine == true) {
              tmp_cur_status = "在线 已断开";
            }
  
            if (that.data.current_info.onLine == false) {
              tmp_cur_status = "离线";
            }
  
  
            that.setData({
              current_info: tmp_current_info,
              markers: tmp_markers,
              cur_status: tmp_cur_status
            });
          }
        }, reInterval);
      },
      fail: function (error) {
        console.log(error, "FindDevice error");
      }
    });
  },
  
  setAuto:function(devNo) {
    let that = this;
    that.disLoad();
    that.load("正在操作，请等待！");
  
    if (app.globalData.onlineDevice.indexOf(devNo) === -1) {
      wx.showModal({
        title: '提示',
        content: '当前设备不在线，操作失败',
      })
      
      that.disLoad();
      return;
    }
  
    wx.request({
      //url: 'https://119.3.46.145/server/m_set_dev_auto?devId=' + devNo,
      url:app.globalData.url + "m_set_dev_auto?devId=" + devNo,
      method: 'POST',
      header: var_header,
      success: res => {     
        setTimeout(function () {
          if (app.globalData.autoDevice.indexOf(devNo) === -1) {
            try_times++;
            if (try_times <= retimes) {
              that.setAuto(devNo);
            }
            else {
              try_times = 0;
              wx.showModal({
                title: '提示',
                content: '操作失败',
              });
              that.disLoad();
            }
          }
          else {
            wx.showModal({
              title: '提示',
              content: '操作成功',
            });
            that.disLoad();
            //改变页面值
            let tmp_current_info = that.data.current_info;
            tmp_current_info.auto = true;
  
            that.setData({
              current_info: tmp_current_info
            });
          }
        }, reInterval);
      },
      fail: function (error) {
        console.log(error, "setManual error");
      }
    });
  
    // $.ajax({
    //   url: "/server/m_set_dev_auto",
    //   data: {
    //     devId: devNo
    //   },
    //   type: 'POST',
    //   success: function () {
    //     setTimeout(function () {
    //       if (autoDevice.indexOf(devNo) === -1) {
    //         try_times++;
    //         if (try_times <= retimes) {
    //           SetAuto(devNo);
    //         }
    //         else {
    //           try_times = 0;
    //           alert("操作失败");
    //           disLoad();
    //         }
    //       }
    //       else {
    //         alert("操作成功");
    //         disLoad();
    //       }
    //     }, reInterval);
    //   }
    // });
  },
  
  setManual:function(devNo) {
    let that = this; 
    that.disLoad();
    that.load("正在操作，请等待！");
  
    if (app.globalData.onlineDevice.indexOf(devNo) === -1) {   
      wx.showModal({
        title: '提示',
        content: '当前设备不在线，操作失败'
      })
      that.disLoad();
      return;
    }
  
    wx.request({
      //url: 'https://119.3.46.145/server/m_set_dev_manual?devId=' + devNo,
      url:app.globalData.url + "m_set_dev_manual?devId=" + devNo,
      method: 'POST',
      header: var_header,
      success: res => {
        // let groups = JSON.parse(res.data.data);
        setTimeout(function () {
          if (app.globalData.manualDevice.indexOf(devNo) === -1) {
            try_times++;
            if (try_times <= retimes) {
              that.setManual(devNo);
            }
            else {
              try_times = 0;
              wx.showModal({
                title: '提示',
                content: '操作失败'
              });
             
              that.disLoad();
            }
          }
          else {
            wx.showModal({
              title: '提示',
              content: '操作成功'
            });
            that.disLoad();
  
            //改变页面值
            let tmp_current_info = that.data.current_info;
            tmp_current_info.auto = false;
  
            that.setData({
              current_info: tmp_current_info
            });
          }
        }, reInterval);
      },
      fail: function (error) {
        console.log(error, "setManual error");
      }
    });
  },
  
  //小程序提供的获取当前页中心点的方法
    mapchangeTap: function () {  
      // 中心点
      let that = this;
  
      let mapCtx = wx.createMapContext('myMap');
      that.setData({
        mapCtx: mapCtx
      }); 
  
      mapCtx.getCenterLocation({
        // success(res) {      
        //   const latitude = res.latitude;
        //   const longitude = res.longitude;
        // }
      });
    },
  
  //设置中心点
    getMapCenter:function(){ 
      let that = this;
      let pos_arr = that.data.markers;
      
      let total = pos_arr.length;
      let X = 0, Y = 0, Z = 0;
      pos_arr.forEach(function (item, index) {
        //console.log(item); //这里的item就是从数组里拿出来的每一个每一组     
        let lat, lon, x, y, z;      
        lat = item.latitude * Math.PI / 180;
        lon = item.longitude * Math.PI / 180;
        x = Math.cos(lat) * Math.cos(lon);
        y = Math.cos(lat) * Math.sin(lon);
        z = Math.sin(lat);
        X += x;
        Y += y;
        Z += z;
      });
  
      X = X / total;
      Y = Y / total;
      Z = Z / total;
      let Lon = Math.atan2(Y, X);
      let Hyp = Math.sqrt(X * X + Y * Y);
      let Lat = Math.atan2(Z, Hyp);
      let center_latitude = Lat * 180 / Math.PI;
      let center_longitude = Lon * 180 / Math.PI;
  
      //console.log(center_latitude, "latitude center");
      //console.log(center_longitude, "longitude center");  
      that.setData({
        latitude: center_latitude,
        longitude: center_longitude
      });  
    },
  
  
  //计算地图缩放比
    getMapScale:function(){
      let that = this;
      let pos_arr = that.data.markers; 
      // if(pos_arr.length <=1){
      //   return;
      // }
      
      let max_latitude = 0.0;
      let max_longitude = 0.0;
      let min_latitude = pos_arr[0].latitude;
      let min_longitude = pos_arr[0].longitude;
  
      pos_arr.forEach(function (item, index) {   
        if (item.longitude >= max_longitude) {
          max_longitude = item.longitude;
        }
  
        if (item.latitude >= max_latitude){
          max_latitude = item.latitude ;
        }
  
        if (item.longitude <= min_longitude){
          min_longitude = item.longitude;
        }
  
        if (item.latitude <= min_latitude) {
          min_latitude = item.latitude;
        }    
      });
  
      let distance = that.distance(max_latitude, max_longitude, min_latitude, min_longitude);
      //console.log(distance, "dis");
  
      var zoom = ["50", "100", "200", "500", "1000", "2000", "5000", "10000", "20000", "25000", "50000", "100000", "200000", "500000", "1000000", "3000000"]//级别18到3。 
      let scale = 3; 
      
      for (var i = 0, zoomLen = zoom.length; i < zoomLen; i++) {
        if (zoom[i] - distance > 0) {
          scale = 18 - i + 1;
  
          that.setData({
            scale: scale
          });
  
          //console.log(JSON.stringify(that.data))
          return scale;//之所以会多3，是因为地图范围常常是比例尺距离的10倍以上。所以级别会增加3。  
        }
        
        if (distance>3000000){
          that.setData({
            scale: 3
          });

          return 3
        }
      }
    },
  
  //计算地图上两点距离
    distance: function (la1, lo1, la2, lo2) {
      var La1 = la1 * Math.PI / 180.0;
      var La2 = la2 * Math.PI / 180.0;
      var La3 = La1 - La2;
      var Lb3 = lo1 * Math.PI / 180.0 - lo2 * Math.PI / 180.0;
      var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(La3 / 2), 2) + Math.cos(La1) * Math.cos(La2) * Math.pow(Math.sin(Lb3 / 2), 2)));
      s = s * 6378.137;
      s = Math.round(s * 10000) / 10;
      s = s.toFixed(2);
      return s;
    },
  
    //定位方法
    getUserLocation: function () {
      let that = this;
      wx.getSetting({
        success: (res) => {
          // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面  res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权  res.authSetting['scope.userLocation'] == true    表示 地理位置授权        
          if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
            //未授权
            wx.showModal({
              title: '请求授权当前位置',
              content: '需要获取您的地理位置，请确认授权',
              success: function (res) {
                if (res.cancel) {
                  //取消授权
                  wx.showToast({
                    title: '拒绝授权',
                    icon: 'none',
                    duration: 1000
                  })
                } else if (res.confirm) {
                  //确定授权，通过wx.openSetting发起授权请求
                  wx.openSetting({
                    success: function (res) {
                      if (res.authSetting["scope.userLocation"] == true) {
                        wx.showToast({
                          title: '授权成功',
                          icon: 'success',
                          duration: 1000
                        })
                        //再次授权，调用wx.getLocation的API
                        that.geo();
                      } else {
                        wx.showToast({
                          title: '授权失败',
                          icon: 'none',
                          duration: 1000
                        })
                      }
                    }
                  })
                }
              }
            })
          } else if (res.authSetting['scope.userLocation'] == undefined) {
            //用户首次进入页面,调用wx.getLocation的API
            that.geo();
          }
          else {
            //console.log('授权成功')
            //调用wx.getLocation的API
            that.geo();
          }
        }
      })
    },
  
    // 获取定位城市
    geo: function () {
      let that = this;
      wx.getLocation({
        type: 'wgs84',
        success: function (res) {
          var latitude = res.latitude;
          var longitude = res.longitude;
  
          var speed = res.speed;
          var accuracy = res.accuracy;  
  
          that.setData({
            latitude:res.latitude,
            longitude:res.longitude
          });     
        }
      })
    },  
  
    goTodetail:function(){
      let that = this;
      wx.navigateTo({
        url: '../detail/detail?current_info='+JSON.stringify(that.data.current_info)+"&address="+that.data.address
      })
    },
  
    load:function(s){
      wx.showLoading({
        title: s,
      });
    },
  
    disLoad:function(){
      wx.hideLoading();
    },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    let that = this;
    that.setData({
      dev_list_detail:[],
      is_load_center_scale: false,
      markers:[]
    });

    app.globalData.markers = [];
    clearInterval(timer);

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    let that = this;
    // let wxst = that.data.wxst;
    // wxst.close(res => {
    //   console.info('连接关闭');
    // }); 

    //clearTimeOut(timer); 
    clearInterval(timer);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  getZoom:function(maxLng, minLng, maxLat, minLat) {
    var zoom = ["50", "100", "200", "500", "1000", "2000", "5000", "10000", "20000", "25000", "50000", "100000", "200000", "500000", "1000000", "2000000"]//级别18到3。  
    var pointA = new BMap.Point(maxLng, maxLat);  // 创建点坐标A  
    var pointB = new BMap.Point(minLng, minLat);  // 创建点坐标B  
    var distance = map.getDistance(pointA, pointB).toFixed(1);  //获取两点距离,保留小数点后两位  
    for (var i = 0, zoomLen = zoom.length; i < zoomLen; i++) {
      if (zoom[i] - distance > 0) {
        return 18 - i + 3;//之所以会多3，是因为地图范围常常是比例尺距离的10倍以上。所以级别会增加3。  
      }
    };
  }
})